<template>
  <el-dialog title="添加工单" :visible.sync="showDialog" top="0" :close-on-click-modal="false" width="90%" @close="cancel">
    <div v-if="selectedItem !== null" class="add-list">
      <div class="add-btn">
        <el-button @click="addTask">添加 工单</el-button>
      </div>
      <div v-for="(item, index) in list" :key="item.id" class="list-item">
        <el-divider content-position="left">
          <span>工单{{ index + 1 }}</span>
        </el-divider>
        <AddItem ref="addItem" :batch-id="selectedItem ? selectedItem.batchId : null" :person-list="personList" :product-list="productList" :product-line-list="productLineList" :batch-list="batchList" />
        <div v-if="list.length > 1" class="delete-btn">
          <el-button type="danger" @click="delTask(index)">删除 工单{{ index + 1 }}</el-button>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
      <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import AddItem from '@/views/processing-management/process-task-manage/creation/components/add-item.vue';
import apiTask from '@/api/processing-management/process-task-manage/index';
import { getToken } from '@/utils/auth';
export default {
  components: { AddItem },
  props: {
    value: Boolean,
    productList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    selectedItem: {
      type: Object,
      default: null
    },
    productLineList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    batchList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    personList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      showDialog: false,
      saveLoading: false,
      list: [
        {
          id: this.generateUUID()
        }
      ],
      updateKey: 0
    };
  },
  watch: {
    value(v) {
      this.showDialog = v;
    }
  },
  mounted() {},
  methods: {
    reset() {
      this.list = [
        {
          id: this.generateUUID()
        }
      ];
    },
    async save() {
      const refs = this.$refs.addItem;
      const list = [];
      for (let i = 0; i < refs.length; i++) {
        const element = refs[i];
        const form = await element.validateForm();
        if (form) {
          list.push({ ...form, organizationNo: getToken('organizationNo') });
        }
      }
      let err = '';
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        const startTime = this.$moment(element.startTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
        const endTime = this.$moment(element.endTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
        if (startTime > endTime) {
          err = '开始时间不能大于结束时间';
          break;
        }
      }
      if (err !== '') {
        this.$message.error(err);
        return;
      }
      if (refs.length === list.length) {
        this.saveLoading = true;
        apiTask
          .batchAdd(list)
          .then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.close();
              this.$emit('reflash');
            }
          })
          .finally(_ => {
            this.saveLoading = false;
          });
      }
    },
    addTask() {
      this.list.push({
        id: this.generateUUID()
      });
    },
    delTask(index) {
      this.list.splice(index, 1);
    },
    close() {
      setTimeout(() => {
        this.reset();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
      }, 250);
      this.$emit('input', false);
    },
    generateUUID() {
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16));
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-divider__text {
    background-color: #f0f3f7;
  }
}
.delete-btn {
  text-align: right;
  margin-top: 10px;
}
.add-btn {
  text-align: right;
  margin-bottom: 10px;
}
</style>
